package com.shujia.sql

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.{Column, DataFrame, Row, SparkSession}

object Demo5Burk {
  def main(args: Array[String]): Unit = {

    //1、创建Spark sql环境
    val spark: SparkSession = SparkSession
      .builder()
      .master("local")
      .appName("sql")
      .config("spark.sql.shuffle.partitions", 1) //默认在集群中时200个
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    //读取数据
    val burks: DataFrame = spark
      .read
      .schema("burk STRING,year STRING,tsl01 DOUBLE,tsl02 DOUBLE,tsl03 DOUBLE,tsl04 DOUBLE,tsl05 DOUBLE,tsl06 DOUBLE,tsl07 DOUBLE,tsl08 DOUBLE,tsl09 DOUBLE,tsl10 DOUBLE,tsl11 DOUBLE,tsl12 DOUBLE")
      .option("sep", ",")
      .csv("spark/data/burks.txt")

    burks.createOrReplaceTempView("burks")

    /**
     * 1、统计每个公司每年按月累计收入
     * 输出结果
     * 公司代码,年度,月份,当月收入,累计收入
     *
     */
    spark.sql(
      """
        |select
        |burk,year,month,tsl,
        |sum(tsl) over(partition by burk,year order by month) as lj_tsl
        |from
        |burks
        |lateral view explode(map(1,tsl01,2,tsl02,3,tsl03,4,tsl04,5,tsl05,6,tsl06,7,tsl07,8,tsl08,9,tsl09,10,tsl10,11,tsl11,12,tsl12)) T as month,tsl
        |""".stripMargin) //.show()

    spark.sql(
      """
        |select explode(map(1,100, 2,200 ,3,300, 4, 400))
        |
        |""".stripMargin) //.show()


    val monthMap: Column = map(
      expr("1"), $"tsl01",
      expr("2"), $"tsl02",
      expr("3"), $"tsl03",
      expr("4"), $"tsl04",
      expr("5"), $"tsl05",
      expr("6"), $"tsl06",
      expr("7"), $"tsl07",
      expr("8"), $"tsl08",
      expr("9"), $"tsl09",
      expr("10"), $"tsl10",
      expr("11"), $"tsl11",
      expr("12"), $"tsl12"
    )

    burks
      //一行转换成多行
      .select($"burk", $"year", explode(monthMap) as Array("month", "tsl"))
      //计算累计
      .withColumn("li_tsl", sum($"tsl") over (Window.partitionBy($"burk", $"year").orderBy($"month")))
    // .show()

    /**
     * 2、统计每个公司当月比上年同期增长率
     * 输出结果
     * 公司代码,年度,月度,增长率（当月收入/上年当月收入 - 1）
     */

    burks
      //一行转换成多行
      .select($"burk", $"year", explode(monthMap) as Array("month", "tsl"))
      //获取上年同月的收入
      .withColumn("take_tsl", lag($"tsl", 1, 0) over (Window.partitionBy($"burk", $"month").orderBy($"year")))
      //计算增长率
      .withColumn("p", round($"tsl" / $"take_tsl" - 1, 4))
      .show(100)
  }

}
